extends Panel

@onready var broad_cast_timer: Timer = $BroadCastTimer

@onready var create_room_button: Button = $RoomContainer/RoomBox/CreateRoomHBox/CreateRoomButton
@onready var create_room_line_edit: LineEdit = $RoomContainer/RoomBox/CreateRoomHBox/CreateRoomLineEdit
@onready var room_list: VBoxContainer = $RoomContainer/RoomBox/RoomList
@onready var start_game_button: Button = $RoomContainer/RoomBox/CreateRoomHBox/StartGameButton



var room_tscn := preload("res://entity/ui/room.tscn")




func _ready() -> void:
	Game.setup_listener()


func _process(_delta: float) -> void:
	show_server_list()


func show_server_list() -> void:
	if Game.listener.get_available_packet_count():
		var server_ip := Game.listener.get_packet_ip()
		var packet := Game.listener.get_packet()
		var data_string := packet.get_string_from_utf8()
		#Debug.log_str(["listener info:", data_string])
		if data_string.is_empty(): return
		var data_room : Dictionary = JSON.parse_string(data_string)
		var real_ip : String = server_ip if server_ip else data_room.ip
		
		var room : Control
		var room_key := "ROOM_" + real_ip.md5_text()
		if room_list.has_node(room_key):
			room = room_list.get_node(room_key)
		else:
			room = room_tscn.instantiate()
			room.name = room_key
			room_list.add_child(room)
		room.get_node("ShowTimer").start()
		room.get_node("Ip").text = real_ip
		room.get_node("Port").text = str(Game.SERVER_PORT)
		room.get_node("Name").text = data_room.name
		room.get_node("Count").text = str(data_room.count)
		room.get_node("Status").text = Game.room_status[data_room.status]
		room.get_node("Level").text = "关卡" + str(data_room.level)
		if multiplayer.get_unique_id() > 0 and multiplayer.get_unique_id() in Game.player_peer_ids:
			room.get_node("Opt/JoinGame").hide()

func _on_broad_cast_timer_timeout() -> void: 
	if visible:
		Game.push_packet()



func _exit_tree() -> void:
	Game.clean_server()
	broad_cast_timer.stop()




func _on_create_room_button_button_down() -> void:
	Game.setup_broadcast(create_room_line_edit.text + "的房间")
	create_room_button.text = "更新房间"
	start_game_button.disabled = false
	broad_cast_timer.start()



func _on_start_game_button_button_down() -> void:
	Game.start_game.rpc(Game.GameType.WLAN)



func _on_back_button_button_down() -> void:
	Game.set_state(Game.GameState.HALL)
